package cn.com.stary1993.kite.captcha.demo.controller;

import cloud.tianai.captcha.common.response.ApiResponse;
import cn.com.stary1993.kite.captcha.support.behavior.BehaviorImageCaptcha;
import cn.com.stary1993.kite.captcha.support.behavior.BehaviorImageCaptchaTrack;
import cn.com.stary1993.kite.captcha.support.simple.SimpleImageCaptcha;
import cn.com.stary1993.kite.captcha.support.simple.SimpleImageCaptchaType;
import cn.com.stary1993.kite.captcha.vo.BehaviorCaptchaVO;
import cn.com.stary1993.kite.captcha.vo.CaptchaResponse;
import cn.com.stary1993.kite.captcha.vo.SimpleCaptchaVO;
import lombok.RequiredArgsConstructor;
import lombok.SneakyThrows;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;

@CrossOrigin
@RequiredArgsConstructor
@RestController
@RequestMapping("/captcha")
public class CaptchaDemoController {

    private final SimpleImageCaptcha simpleImageCaptcha;

    private final BehaviorImageCaptcha behaviorImageCaptcha;


    @SneakyThrows
    @GetMapping("/simple/gen1")
    public void genSimpleImageCaptchaStream(HttpServletResponse response, @RequestParam("type") String type, String timestamp) {
        simpleImageCaptcha.out(SimpleImageCaptchaType.valueOf(type), timestamp, response.getOutputStream());
    }


    @PostMapping("/simple/check1")
    public Boolean checkSimpleImageCaptchaStream(@RequestParam("type") String type, String timestamp, @RequestParam("code") String code) {
        return simpleImageCaptcha.verify(SimpleImageCaptchaType.valueOf(type), timestamp, code);
    }


    @GetMapping("/simple/gen2")
    public CaptchaResponse<SimpleCaptchaVO> genSimpleImageCaptcha(@RequestParam("type") String type, @RequestParam("timestamp") String timestamp) {
        return simpleImageCaptcha.generate(SimpleImageCaptchaType.valueOf(type), timestamp);
    }

    @PostMapping("/simple/check2")
    public Boolean checkSimpleImageCaptcha(@RequestParam("id") String id, @RequestParam("type") String type, @RequestParam("timestamp") String timestamp, @RequestParam("code") String code) {
        return simpleImageCaptcha.verify(id, SimpleImageCaptchaType.valueOf(type), timestamp, code);
    }

    @GetMapping("/behavior/gen")
    public CaptchaResponse<BehaviorCaptchaVO> genBehaviorImageCaptcha(@RequestParam("type") String type) {
        return behaviorImageCaptcha.generate(type);
    }

    @PostMapping("/behavior/check")
    public ApiResponse checkBehaviorImageCaptcha(@RequestParam("id") String id, @RequestBody BehaviorImageCaptchaTrack imageCaptchaTrack) {
        return behaviorImageCaptcha.matching(id, imageCaptchaTrack);
    }

}
